import os
import json
import re

# ====== 用户自定义区域：请根据实际情况修改以下路径 ======
INPUT_DIR = r"C:\Users\admin\Desktop\新合并\曲线"  # 输入 JSON 文件所在的文件夹
OUTPUT_FILE = r"C:\Users\admin\Desktop\新合并\out_put.json"  # 输出文件完整路径
# =========================================================
def main():
    if not os.path.isdir(INPUT_DIR):
        raise FileNotFoundError(f"输入目录 '{INPUT_DIR}' 不存在")

    pattern = re.compile(r'^(\d+)\.json$')
    files = []
    for fname in os.listdir(INPUT_DIR):
        match = pattern.match(fname)
        if match:
            num = int(match.group(1))
            files.append((num, fname))

    files.sort()
    file_paths = [os.path.join(INPUT_DIR, fname) for _, fname in files]

    merged_data = []
    offset = 0  # 初始偏移量为 0

    for path in file_paths:
        with open(path, 'r', encoding='utf-8') as f:
            data = json.load(f)

        current_array = data.get('a', [])
        if not current_array:
            continue

        # 偏移并合并数据
        adjusted = [[row[0] + offset, row[1]] for row in current_array]
        merged_data.extend(adjusted)

        # 更新偏移量：基于处理后的最后一个键值 + 100
        if adjusted:
            last_key_after_offset = adjusted[-1][0]
            offset = last_key_after_offset + 100

    # 自动创建输出目录
    os.makedirs(os.path.dirname(OUTPUT_FILE), exist_ok=True)

    # 保存结果
    with open(OUTPUT_FILE, 'w', encoding='utf-8') as f:
        json.dump({"a": merged_data}, f, indent=2)

    print(f"✅ 合并完成，结果已保存至: {OUTPUT_FILE}")

if __name__ == '__main__':
    main()